import Api from '../../utils/http/api'
import common_utils from '../../utils/common_utils'
let waterfallLayout = null
const app = getApp()
Page({
  data: {
    recommendList: [], //banner图数据源
    productsList: [], //瀑布流数据源
    pageNum: 1, //分页 页码
    pageSize: 10, //分页 页面size
    hasLoadMore: false //是否可以加载更多

  },
  onLoad(options) {
    this.getRecommend() //调用 获取banner数据的接口
    this.getProducts() //调用 获取瀑布流组件的接口
    waterfallLayout = this.selectComponent('#waterfallLayout'); //根据id拿到瀑布流组件的实例
  },
  // 加载更多
  onReachBottom() {
    if (this.data.hasLoadMore) {
      this.getProducts()
    }
  },
  //下拉刷新
  onPullDownRefresh() {
    this.setData({
      hasLoadMore: false,
      recommendList: [],
      productsList: [],
      pageNum: 1,
    })
    this.getRecommend()
    this.getProducts()
  },
  // 分享
  onShareAppMessage: function () {
    return {
      title: '物美价廉，一省到底～',
      imageUrl: 'https://oss.eetop.com/bewt365/d2244f94d1824aa64672544fb4b0bc9d.jpg',
      path: '/pages/home/home'
    }
  },
  //商品item 点击
  onProduct(e) {
    // console.log(e.detail.item)
    let obj = e.detail.item
    wx.navigateTo({
      url: '/package_shop/pages/product/product?id=' + obj.id,
    })
  },

  //------------ 获取接口数据 ------------
  // 获取 banner
  getRecommend() {
    let params = {}
    Api.getRecommend(params).then(res => {
      let list = res.data
      list.forEach((item) => {
        if (item.picture) {
          item.picture = common_utils.getApiImg(item.picture)
        }
      })
      this.setData({
        recommendList: list
      })


    }).catch(err => console.log(err))
  },
  // 获取为你推荐列表
  getProducts() {
    this.setData({
      hasLoadMore: false
    })
    let params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      category: 0
    }
    Api.getProducts(params).then(res => {
      let list = res.data
      list.forEach((item) => {
        if (item.picture) {
          item.picture = common_utils.getApiImg(item.picture)
        }
      })

      this.setData({
        productsList: this.data.productsList.concat(list)
      })


      if (this.data.pageNum === 1) {
        // 获取接口数据后使用瀑布流组件start方法，刷新瀑布流
        waterfallLayout.start(list).then(() => {
          this.setData({
            pageNum: list.length >= 10 ? this.data.pageNum + 1 : this.data.pageNum,
            hasLoadMore: list.length >= this.data.pageSize
          })

        })
      } else {
        // 获取接口数据后使用瀑布流组件append方法，当append完成后调用then，是否可触底价在的标志位可以在这里处理
        waterfallLayout.append(list).then(() => {
          this.setData({
            pageNum: list.length >= this.data.pageSize ? this.data.pageNum + 1 : this.data.pageNum,
            hasLoadMore: list.length >= this.data.pageSize
          })
        })

      }

    }).catch(err => console.log(err))
  },
});
